package com.sunday.scoremanager.ui;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.common.widgets.PasswordInputEdt;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.entity.BankAccount;
import com.sunday.scoremanager.entity.Income;
import com.sunday.scoremanager.http.ApiClient;

import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/11/1.
 */

public class WithDrawScoreProfitActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.edit_profit)
    ClearEditText editProfit;
    @Bind(R.id.available_profit)
    TextView availableProfit;
    @Bind(R.id.cb_exchange)
    CheckBox cbExchange;
    @Bind(R.id.cb_withdraw)
    CheckBox cbWithdraw;
    @Bind(R.id.btn_next)
    TextView btnNext;

    private String availbleMoney;

    private BankAccount account;
    private long memberId;
    private int isSetTradePwd;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdraw_score_profit);
        ButterKnife.bind(this);
        account = (BankAccount) getIntent().getSerializableExtra("item");
        memberId = BaseApp.getInstance().getMember().getSellerId();
        isSetTradePwd = BaseApp.getInstance().getMember().getIsSetTradePassword();
        initView();
        getAvailableMoney();
    }

    Income income;

    private void getAvailableMoney() {
        showLoadingDialog(0);
        Call<ResultDO<Income>> call = ApiClient.getApiAdapter().myAssets(memberId, 5, 2);
        call.enqueue(new Callback<ResultDO<Income>>() {
            @Override
            public void onResponse(Call<ResultDO<Income>> call, Response<ResultDO<Income>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0 || response.body().getResult() != null) {
                    income = response.body().getResult();
                    availableProfit.setText("可提现金额￥" + income.getNowIncome().setScale(2, RoundingMode.HALF_UP));

                }
            }

            @Override
            public void onFailure(Call<ResultDO<Income>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
                dissMissDialog();
            }
        });
    }

    private void initView() {
        titleView.setText("提现");
        rightTxt.setText("提现记录");
    }


    private String withDrawMoney;
    private final static int REQUEST_BANK = 0x1111;

    @OnClick({R.id.rightTxt, R.id.btn_next})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.rightTxt:
                intent = new Intent(mContext, CashRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_next:
                withDrawMoney = editProfit.getText().toString();
                if (Double.parseDouble(withDrawMoney) > Double.parseDouble(income.getNowIncome().toString())) {
                    ToastUtils.showToast(mContext, "超出最大提现金额！");
                    return;
                }
                if (TextUtils.isEmpty(withDrawMoney)) {
                    ToastUtils.showToast(mContext, "请填写提现金额");
                    return;
                }
                if (Double.parseDouble(withDrawMoney) <= 0) {
                    ToastUtils.showToast(mContext, "暂无可提现金额");
                    return;
                }

                if (isSetTradePwd == 1) {
                    //有支付密码 密码验证
                    showPayPwdDialog();
                } else {
                    showSettingDialog();
                }
                break;
        }
    }

    private String payPwd;

    private void showPayPwdDialog() {
        final AlertDialog myDialog = new AlertDialog.Builder(mContext).create();
        myDialog.setView(((Activity) mContext).getLayoutInflater().inflate(R.layout.pop_pay, null));
        myDialog.show();
        myDialog.getWindow().setContentView(R.layout.pop_pay);
        myDialog.getWindow().setGravity(Gravity.CENTER);
        TextView dismiss = (TextView) myDialog.getWindow().findViewById(R.id.dismiss);
        TextView confirm = (TextView) myDialog.getWindow().findViewById(R.id.confirm);
        TextView forgetPwd = (TextView) myDialog.getWindow().findViewById(R.id.forget_pwd);
        final PasswordInputEdt edtPassword = (PasswordInputEdt) myDialog.getWindow().findViewById(R.id.edt_password);
        final InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edtPassword, InputMethodManager.SHOW_IMPLICIT);
        edtPassword.setOnInputOverListener(new PasswordInputEdt.onInputOverListener() {
            @Override
            public void onInputOver(String text) {
                payPwd = text;
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(payPwd)) {
                    ToastUtils.showToast(mContext, "请输入支付密码");
                    return;
                }
                withDraw(1);
                imm.hideSoftInputFromWindow(edtPassword.getWindowToken(), 0);
                myDialog.dismiss();
            }
        });
        dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imm.hideSoftInputFromWindow(edtPassword.getWindowToken(), 0);
                myDialog.dismiss();
            }
        });

        forgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(mContext, SettingPayPwdActivity.class);
                intent.putExtra("fromWithDraw", true);
                intent.putExtra("type", 2);
                startActivityForResult(intent, REQUEST_PWD);
            }
        });
    }


    private final static int REQUEST_PWD = 0x1113;

    private void showSettingDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示");
        builder.setMessage("暂未设置交易密码");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                intent = new Intent(mContext, SettingPayPwdActivity.class);
                intent.putExtra("fromWithDraw", true);
                startActivityForResult(intent, REQUEST_PWD);
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        isSetTradePwd = BaseApp.getInstance().getMember().getIsSetTradePassword();
        showPayPwdDialog();

    }

    private void withDraw(int selectType) {
        //提现或者兑换
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().makeCash(memberId, account.getId(), withDrawMoney, payPwd, selectType, 2, 3);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "提现成功");
                    finish();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }
}